package com.example.yt_app.Othre;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

import com.example.yt_app.Interface.SB_HttpBinService;
import com.example.yt_app.Interface.WeatherService;
import com.example.yt_app.R;
import com.example.yt_app.Urils.Delay;
import com.example.yt_app.Urils.Json;
import com.example.yt_app.Urils.SB_Parameter;
import com.example.yt_app.Urils.State;
import com.example.yt_app.bean.City_weather.City_weather;
import com.example.yt_app.bean.HistoricalData.HistoricalJsonRootBean;
import com.example.yt_app.bean.Onenet.Data;
import com.example.yt_app.bean.Onenet.JsonRootBean;
import com.example.yt_app.bean.OnenetSb.OnenetSbJsonRootBean;
import com.example.yt_app.bean.Onenet_online.Devices;
import com.example.yt_app.bean.Onenet_online.Online_json;
import com.example.yt_app.bean.PutOneentmassage.PutOnenetJsonRootBean;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;


import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by dell on 2021/7/16.
 */
@SuppressWarnings("ALL")
public class Oennet extends AppCompatActivity {

    private static final String TAG = "Rxjava";
    private OkHttpClient okHttpClient;
    Request request = new Request.Builder()
            .url("http://api.heclouds.com/devices/status?" +"devIds="+
                    State.DeviceIDs )
            .header("api-key", com.example.yt_app.Urils.State.ApiKey).build();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.onenet);
        //绑定控件
        ButterKnife.bind(this);
        okHttpClient = new OkHttpClient();
    }

    /**
     *  RX
     * */
    public void dd(){
        String s ="{led1:1,humidity:95.2%}";
        byte[] data = s.getBytes();
        Request request = new Request.Builder()
                .url("http://api.heclouds.com/devices/" + DeviceID
                        + "/datapoints?type=3")
                .addHeader("Content-Length", String.valueOf(data.length))
                .header("api-key", State.ApiKey).build();

        Call call =okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
                    /*response.body().string()中的 (.string)只能使用一次*/
                    Log.i(TAG , "postAsync" + response.body().string());
//                    String responseData = response.body().string();
//                    JsonRootBean app = Json.gson.fromJson(responseData, JsonRootBean.class);
//                    List<Data> streams = (List<Data>) app.getData();
//                    System.out.println(streams.get(0).getUnit_symbol());
                    //String wendu = streams.get(0).getCurrent_value()+streams.get(0).getUnit_symbol();
                    // shidu = streams.get(1).getCurrent_value()+streams.get(1).getUnit_symbol();

                } catch (IOException e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

        });

    }
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @OnClick(R.id.button4)
    /**
     *  RX
     * */
    public void RxAsync(){

        //步骤4：创建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.heclouds.com/") // 设置 网络请求 Url
                .addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析(记得加入依赖)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        // 步骤5：创建 网络请求接口 的实例
        SB_HttpBinService request = retrofit.create(SB_HttpBinService.class);
        // 步骤6：采用Observable<...>形式 对 网络请求 进行封装
        Observable<HistoricalJsonRootBean> observable = request.getSbMessage(State.ApiKey,"2021-07-30T08:00:35","2021-07-28T08:00:35");
        System.out.println(State.DeviceIDs);
        // 步骤7：发送网络请求
        observable.subscribeOn(Schedulers.io())               // 在IO线程进行网络请求
                .observeOn(AndroidSchedulers.mainThread())  // 回到主线程 处理请求结果
                .subscribe(new Observer<HistoricalJsonRootBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.d("TAG", "开始采用subscribe连接");
                    }

                    @Override
                    public void onNext(@NotNull HistoricalJsonRootBean historicalJsonRootBean) {
                        Log.i("gg",historicalJsonRootBean.toString());
                        //List<Devices> devices = historicalJsonRootBean.getData().getDevices();


                    }


                    @Override
                    public void onError(Throwable e) {
                        Log.d("TAG," ,"请求失败");
                    }

                    @Override
                    public void onComplete() {
                        Log.d("TAG", "请求成功");
                    }
                });
    }
    /*



    /**
     *  RX
     * */


    @SuppressWarnings("AlibabaConstantFieldShouldBeUpperCase")
    private static final String DeviceID = "735471469";
    // 个人使用就建议填产品key,设备key在二进制获取那里会权限不足
    @SuppressWarnings({"AlibabaConstantFieldShouldBeUpperCase", "AlibabaCommentsMustBeJavadocFormat"})
    private static final String ApiKey = "FN8vCnpwAjyjTV2m1y=zpL451i4=";
    @SuppressWarnings("AlibabaAvoidManuallyCreateThread")
    @OnClick(R.id.button5)
    public void ddd(){
        //noinspection AlibabaAvoidManuallyCreateThread
        new Thread()
        {
            @SuppressWarnings("AlibabaUndefineMagicConstant")
            @Override
            public void run() {
                URL url;
                HttpURLConnection connection;
                try {
                    //data1代表云端的数据流是data1
                    String s1 = new String(",;" + "led1" + "," + "0");
                    byte[] data = s1.getBytes();
                    // 先new出一个URL对象，传入网络地址
                    // 调用openConnection()方法获取到HttpURLConnection对象
                    // 自己创建的中移物联网的地址http://api.heclouds.com/devices/25857699/datapoints?type=5
                    url = new URL("http://api.heclouds.com/devices/" + DeviceID
                            + "/datapoints?type=5");
                    connection = (HttpURLConnection) url.openConnection();
                    // 下面使一些自由的定制，比如设置连接超时，读取超时的毫秒数，以及服务器希望得到的一些消息头
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("api-key", ApiKey);
                    connection.setRequestProperty("Content-Length",
                            String.valueOf(data.length));
                    connection.setChunkedStreamingMode(5);
                    // 设置打开输出流
                    connection.setDoOutput(true);
                    // 拿到输出流
                    OutputStream os = connection.getOutputStream();
                    // 使用输出流往服务器提交数据
                    os.write(data);
                    os.flush();
                    os.close();
                    // //如果请求发送成功
                    //noinspection AlibabaUndefineMagicConstant
                    if (connection.getResponseCode() == 200) {

                        // 接下来利用输入流对数据进行读取
                        InputStream is = connection.getInputStream();
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(is));
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = br.readLine()) != null) {
                            response.append(line);
                        }// 正常则返回{"errno":0,"error":"succ"}，此函数为void，用不上这个


                    }

                    // 最后关闭HTTP连接
                    connection.disconnect();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }
}




